package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxh
 * @since 2022-7-28
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private IFollowService followService;
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        //records.forEach(this::queryBlogUser);
        records.forEach(blog ->{
            queryBlogUser(blog);
            UserDTO user = UserHolder.getUser();
            //如果当前用户未登录直接返回，无需查询当前用户是否已经点赞
            if(user==null){
                return;
            }
            Long userId = user.getId();
            //查询当前用户是否已经点赞
            Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + blog.getId(), userId.toString());
            blog.setIsLike(score!=null);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //1.查询blog
        Blog blog = getById(id);
        if(blog==null){
            return Result.fail("笔记不存在！");
        }
        queryBlogUser(blog);
        UserDTO user = UserHolder.getUser();
        //当前用户未登录，无需查询是否是否已经点赞
        if(user==null){
            Result.ok(blog);
        }
        Long userId = user.getId();
        //查询当前用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userId.toString());
        blog.setIsLike(score!=null);
        return Result.ok(blog);
    }

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result likeBlog(Long id) {
        UserDTO user = UserHolder.getUser();
        if(user==null){
            //用户未登录，无需查询是否点赞
            return Result.ok();
        }
        //1.获取当前登陆用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userId.toString());
        //3.当前用户没有点赞
        if(score==null){
            //3.1数据库点赞数+1
            boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            //3.2保存用户数据到Redis set当中  zadd key value score
            if(isSuccess){
                stringRedisTemplate.opsForZSet().add(BLOG_LIKED_KEY+id,userId.toString(),System.currentTimeMillis());
            }
        }else{
            //4.已经点赞
            //4.2数据库点赞数数量-1
            boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            //4.3把用户从Redis set集合中移除
            stringRedisTemplate.opsForZSet().remove(BLOG_LIKED_KEY+id,userId.toString());
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1.查询top的点赞用户  zrange key 0  4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY + id, 0, 4);
        if(top5==null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //2.解析出用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //3.根据用户id查询用户
        String idStr = StrUtil.join(",", ids);
        //List<UserDTO> userDTOS = userService.listByIds(ids)
        List<UserDTO> userDTOS = userService.query()
                .in("id",ids).last("order by field (id,"+idStr+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        //1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2.保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败");
        }
        //3.查询笔记作者的所有粉丝 select * from tb_follow where follow_user_id = ?
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        ///4。推送笔记给所有粉丝
        for(Follow follow: follows){
            //4。1 获取粉丝id
            Long userId = follow.getUserId();
            //4.2 推送
            stringRedisTemplate.opsForZSet().add(FEED_KEY+userId,blog.getId().toString(),System.currentTimeMillis());
        }

        //4.推送笔记id给所有粉丝
        //3.返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱 zrevrangebyscore key max min withscores limit offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(FEED_KEY + userId, 0, max, offset, 2);
        if(typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        List<Long> ids=new ArrayList<>(typedTuples.size());
        long minTime=0;
        int os=1; //当前最小元素的最小值的个数
        //3.解析收件箱 blogId minTime-score-(时间戳) offset 当前最小元素的最小值的个数
        for(ZSetOperations.TypedTuple<String> tuple: typedTuples){
            //4.1获取id
            String idStr=tuple.getValue();
            ids.add(Long.valueOf(idStr));
            long time = tuple.getScore().longValue();
            if(time==minTime){
                os++;
            }else{
                //4.2获取分数(时间戳)
                minTime=time;
                os=1;
            }
        }
        //4.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id",ids)
                .last("order by field(id,"+idStr+")").list();

        //每一条博客的用户名称与图标，以及当前用户是否点赞
        for(Blog blog:blogs){
            queryBlogUser(blog);
            //查询当前用户是否已经点赞
            Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + blog.getId(), userId.toString());
            blog.setIsLike(score!=null);
        }
        //5.封装并返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);
        log.debug(os+"");
        log.debug(minTime+"");
        return Result.ok(r);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
